import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:interrogation/src/base/utils/logger.dart';
import 'package:interrogation/src/data/models/char_record_res.dart';
import 'package:interrogation/src/data/models/get_info_res.dart';

import 'package:interrogation/src/module/const.dart';

import '../../../../base/utils/socket.dart';
import '../../../../base/utils/storage_manager.dart';
import '../../../../data/api.dart';
import '../../../../main_service.dart';

class ChatDetailPageController extends GetxController {
  FocusNode focusNode = FocusNode();
  late IMSocket socket;
  TextEditingController textEditingController = TextEditingController();
  int cid = 0; //问诊记录id
  int receiverId = 0;
  String receiverName = "";
  String receiverAvatar = "";
  int senderId = 0;
  String senderName = "";
  String senderAvatar = "";

  // Message list and pagination
  var list = <ChatMessage>[].obs;
  EasyRefreshController refreshController = EasyRefreshController(
    controlFinishLoad: true,
    controlFinishRefresh: true,
  );
  int page = 1;
  int pageSize = 20;
  int total = 0;
  bool isLoading = false;
  bool hasMore = true;

  @override
  void onInit() {
    super.onInit();
    _parseArguments();
    _initSocket();
    onRefresh();
  }

  @override
  void onClose() {
    super.onClose();
    socket.disconnect();
    refreshController.dispose();
    textEditingController.dispose();
    focusNode.dispose();
  }

  void _parseArguments() {
    var data = Get.arguments;
    cid = (data["cid"] ?? 0) as int;
    receiverId = (data["receiverId"] ?? 0) as int;
    receiverName = (data["receiverName"] ?? '');
    receiverAvatar = (data["avatar"] ?? "");
    UserInfo userInfo = Get.find<MainService>().userInfo;
    senderId = userInfo.id ?? 0;
    senderName = userInfo.nickname ?? '';
    senderAvatar = userInfo.avatar ?? '';
  }

  void _initSocket() {
    String? token = StorageManager.getString(StorageConst.token);
    socket = IMSocket.init(AppConst.socketServerUrl + "?token=${token ?? ''}");
    loggy.info("socketAddress is: ${AppConst.socketServerUrl + "?token=${token ?? ''}"}");
    print("socketAddress is: ${AppConst.socketServerUrl + "?token=${token ?? ''}"}");
    socket.messageStream.listen((String event) {
      loggy.info("messageStream is: $event");
      try {
        Map<String, dynamic> data = jsonDecode(event);
        if (data['type'] == 'chat-message-receive') {
          Map<String, dynamic> content = jsonDecode(data['content']);
          ChatMessage message = ChatMessage.fromJson(content);
          if (message.cid == cid) {
            list.insert(0, message);
          }
        }
      } catch (e) {
        loggy.error("Error parsing socket message: $e");
      }
    });
  }

  void sendMsg() {
    String message = textEditingController.text.trim();
    if (message.isEmpty) return;

    Map<String, dynamic> data = {
      "type": "chat-message-send",
      "content": jsonEncode({
        "cid": cid,
        "senderId": senderId,
        "receiverId": receiverId,
        "messageContent": message,
        "messageType": 1,
        "createTime": DateTime.now().toIso8601String(),
      })
    };

    socket.send(data);
    textEditingController.clear();
    focusNode.unfocus();

    // Add message to list immediately
    list.insert(0, ChatMessage(
      cid: cid,
      senderId: senderId,
      receiverId: receiverId,
      messageContent: message,
      messageType: 1,
    //  createTime: DateTime.now().toString(),
    ));
  }

  Future<void> onRefresh() async {
    if (isLoading) return;
    isLoading = true;

    try {
      page = 1;
      hasMore = true;
      EasyLoading.show(status: '加载中...');
      
      CharRecordRes? res = await Api.getChatMessageList(
        cid,
        page: page,
        pageSize: pageSize,
      );

      if (res?.data?.list != null) {
        list.value = res!.data!.list!;
        total = res.data?.total ?? 0;
        hasMore = list.length < total;
      }
    } catch (e) {
      loggy.error("Error refreshing messages: $e");
      BrnToast.show("加载失败，请重试", Get.context as BuildContext);
    } finally {
      isLoading = false;
      refreshController.finishRefresh();
      refreshController.resetFooter();
      EasyLoading.dismiss();
    }
  }

  Future<void> onLoad() async {
    if (isLoading || !hasMore) {
      refreshController.finishLoad(IndicatorResult.success);
      return;
    }

    isLoading = true;
    try {
      page++;
      EasyLoading.show(status: '加载中...');
      
      CharRecordRes? res = await Api.getChatMessageList(
        cid,
        page: page,
        pageSize: pageSize,
      );

      if (res?.data?.list != null) {
        list.addAll(res!.data!.list!);
        total = res.data?.total ?? 0;
        hasMore = list.length < total;
      }
    } catch (e) {
      loggy.error("Error loading more messages: $e");
      page--;
      BrnToast.show("加载失败，请重试", Get.context as BuildContext);
    } finally {
      isLoading = false;
      refreshController.finishLoad(
        hasMore ? IndicatorResult.success : IndicatorResult.noMore
      );
      EasyLoading.dismiss();
    }
  }
}
